import importlib
import inspect
import re
import os
from django.http import JsonResponse

def get_api(fullname):
    """Get the api module."""
    try:
        module_name, api_name = ".".join(fullname.split('.')[:-1]), fullname.split('.')[-1]
        # pylint: disable=unused-variable
        module_import = importlib.import_module(module_name)
    except ModuleNotFoundError:
        module_name, api_name = ".".join(fullname.split('.')[:-2]), ".".join(fullname.split('.')[-2:])
        module_import = importlib.import_module(module_name)
    # pylint: disable=eval-used
    api = eval(f"module_import.{api_name}")
    return api


def get_api_info(api_name):
    module_api = get_api(api_name)
    try:
        py_docs = inspect.getdoc(module_api)
    except TypeError:
        try:
            py_docs = inspect.getdoc(inspect.getmodule(module_api))
        except TypeError:
            py_docs = ''
    try:
        if api_name.lower() != api_name:
            source_code = inspect.getsource(module_api.__init__)
        else:
            source_code = inspect.getsource(module_api)
        if module_api.__doc__:
            source_code = source_code.replace(module_api.__doc__, '')
        all_params_str = re.findall(r"def [\w_\d\-]+\(([\S\s]*?)(\):|\) ->.*?:)", source_code)
        all_params = re.sub("(self,)|(self, )|(cls,)|(cls, )", '', all_params_str[0][0].replace("\n", ""))
    except:
        all_params = ''

    return py_docs, all_params

if __name__ == "__main__":
    apiname = input('请输入可调用的接口名全称：')
    doc, params = get_api_info(apiname)
    print(f'接口注释：{doc}')
    print(f'参数：{params}')